package main

import (
	"flag"
	"strconv"
	"time"

	"net"
	"os"

	"regexp"
	"strings"

	"github.com/gookit/color"
)

var ip = flag.String("a", "", "ip address for check, for example: 10.1.203.11")
var port = flag.String("p", "", "port for check, for example: 80")

func checkIpPort(url string) {
	_, err := net.DialTimeout("tcp", url, time.Second*3)
	if err != nil {
		color.Red.Println(err)
	} else {
		color.Green.Println("Open")
	}
}

func checkIpOk(ips string) bool {
	addr := strings.Trim(ips, " ")
	regStr := `^(([1-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.)(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){2}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$`
	if match, _ := regexp.MatchString(regStr, addr); match {
		return true
	}
	return false
}

func checkPortOk(port string) bool {
	int_port, _ := strconv.Atoi(port)
	if int_port > 1 && int_port <= 65535 {
		return true
	}
	return false

}
func main() {

	if len(os.Args) != 5 {
		color.Red.Println("错误：请输入完整的项，包含IP地址和端口.")
		flag.Usage()
		return
	}

	if checkIpOk(os.Args[2]) && checkPortOk(os.Args[4]) {
		flag.Parse()

		ip := *ip
		port := *port
		url := ip + ":" + port

		checkIpPort(url)

	} else {

		color.Red.Println("错误：IP地址或端口输入错误，请验证后重新尝试")
	}

}
